package com.example.museum.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.museum.entity.Product;
import com.example.museum.entity.ProductAppraise;
import com.example.museum.entity.User;
import com.example.museum.mapper.ProductAppraiseMapper;
import com.example.museum.mapper.ProductMapper;
import com.example.museum.mapper.UserMapper;
import com.example.museum.service.ProductService;
import com.example.museum.vo.ProductAppraiseVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;

@Service
public class ProductServiceImpl extends ServiceImpl<ProductMapper,Product> implements ProductService {

    @Autowired
    private ProductMapper productMapper;
    @Autowired
    private ProductAppraiseMapper  productAppraiseMapper;
    @Autowired
    private UserMapper userMapper;

    @Override
    public List<Product> getlist() {

        LambdaQueryWrapper<Product> productLambdaQueryWrapper = new LambdaQueryWrapper<>();
        List<Product> products = productMapper.selectList(productLambdaQueryWrapper);

        return products;
    }

    @Override
    public void addendAppraise(ProductAppraise productAppraise) {
        productAppraiseMapper.insert(productAppraise);
    }

    @Override
    public List<ProductAppraiseVo> getapprasielist(Long productId) {


        // 查询所有与该商品关联的评价
        LambdaQueryWrapper<ProductAppraise> productLambdaQueryWrapper = new LambdaQueryWrapper<>();
        productLambdaQueryWrapper.eq(ProductAppraise::getProductId, productId);

        // 获取所有评价记录
        List<ProductAppraise> productAppraises = productAppraiseMapper.selectList(productLambdaQueryWrapper);

        // 用来存放最终返回的DTO数据
        List<ProductAppraiseVo> result = new ArrayList<>();

        // 遍历每个评价记录
        for (ProductAppraise productAppraise : productAppraises) {
            Long userId = productAppraise.getUserId();

            // 根据userId查询用户信息
            LambdaQueryWrapper<User> userLambdaQueryWrapper = new LambdaQueryWrapper<>();
            userLambdaQueryWrapper.eq(User::getId, userId);
            User user = userMapper.selectOne(userLambdaQueryWrapper);

            ProductAppraiseVo appraise = ProductAppraiseVo.builder()
                    .id(productAppraise.getId())
                    .rating(productAppraise.getRating())
                    .content(productAppraise.getContent())
                    .build();

            if (user != null) {
                appraise.setUsername(user.getName());
            } else {
                appraise.setUsername("未知用户");
            }

            // 将DTO添加到结果列表
            result.add(appraise);
        }

        // 返回封装好的结果
        return result;
    }

    @Override
    public Page<Product> getpageList(int page, int pageSize, String query) {

        Page<Product> productPage = new Page<>(page, pageSize);

        LambdaQueryWrapper<Product> productLambdaQueryWrapper = new LambdaQueryWrapper<>();

        if(query != null && StringUtils.isNotEmpty(query)){
            productLambdaQueryWrapper.like(Product::getName, query);
        }
        Page<Product> selectPage = productMapper.selectPage(productPage, productLambdaQueryWrapper);

        return selectPage;
    }

    @Override
    public void addproduct(Product product) {

        product.setCreateTime(LocalDateTime.now());

        productMapper.insert(product);

    }

    @Override
    public void updateProduct(Product product) {

        product.setUpdateTime(LocalDateTime.now());
        LambdaUpdateWrapper<Product> productLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        productLambdaUpdateWrapper.eq(Product::getId, product.getId());
        productMapper.update(product, productLambdaUpdateWrapper);
    }

    @Override
    public void deleteByid(Long id) {

        LambdaQueryWrapper<Product> productLambdaQueryWrapper = new LambdaQueryWrapper<>();

        productLambdaQueryWrapper.eq(Product::getId, id);

        Product product = productMapper.selectOne(productLambdaQueryWrapper);

        String imageAddress = product.getImage();

        if (imageAddress != null && !imageAddress.isEmpty()) {

            Path imagePath = Paths.get("D:/IDEA/Graduation project/Museum/src/main/resources/static"+ imageAddress);

            try {
                // 删除图片文件
                Files.delete(imagePath);
                System.out.println("图片删除成功: " + imagePath);
            } catch (IOException e) {
                e.printStackTrace();
                System.err.println("删除图片失败: " + imagePath);
            }
        }

        LambdaUpdateWrapper<Product> productLambdaUpdateWrapper = new LambdaUpdateWrapper<>();
        productLambdaUpdateWrapper.eq(Product::getId, id);
        productMapper.delete(productLambdaUpdateWrapper);
    }

    @Override
    public Integer gettotalProducts() {
        Integer  totalProducts = productMapper.gettotalProducts();
        return totalProducts;
    }

//    @Override
//    public BigDecimal getProductsGrowthRate(Integer days) {
//        // 实现商品数同比增长率计算
//        // 这里提供一个简单的实现，实际应用中可能需要更复杂的计算逻辑
//        try {
//            // 获取当前商品总数
//            long currentCount = this.count();
//
//            // 如果是测试环境或者没有足够的历史数据，返回一个默认值
//            return new BigDecimal("5.7");
//
//            // 实际实现应该计算前一个周期的商品数，然后计算增长率
//            // 例如：(currentCount - previousCount) / previousCount * 100
//        } catch (Exception e) {
//            // 出现异常时返回0
//            return BigDecimal.ZERO;
//        }
//    }


    @Override
    public Page<ProductAppraiseVo> getAppraisePageList(int page, int pageSize, String query, Integer rating) {
        // 创建分页对象
        Page<ProductAppraise> appraisePage = new Page<>(page, pageSize);
        
        // 构建查询条件
        LambdaQueryWrapper<ProductAppraise> queryWrapper = new LambdaQueryWrapper<>();
        
        // 如果有评分筛选条件，添加评分筛选
        if (rating != null) {
            queryWrapper.eq(ProductAppraise::getRating, rating);
        }
        
        // 如果有查询关键词，需要关联商品表进行查询
        if (query != null && StringUtils.isNotEmpty(query)) {
            // 先查询符合条件的商品ID
            LambdaQueryWrapper<Product> productWrapper = new LambdaQueryWrapper<>();
            productWrapper.like(Product::getName, query);
            List<Product> products = productMapper.selectList(productWrapper);
            
            // 如果没有找到符合条件的商品，返回空结果
            if (products.isEmpty()) {
                return new Page<ProductAppraiseVo>(page, pageSize);
            }
            
            // 提取商品ID列表
            List<Long> productIds = products.stream().map(Product::getId).collect(java.util.stream.Collectors.toList());
            queryWrapper.in(ProductAppraise::getProductId, productIds);
        }
        
        // 执行分页查询
        Page<ProductAppraise> resultPage = productAppraiseMapper.selectPage(appraisePage, queryWrapper);
        
        // 转换为VO对象
        List<ProductAppraiseVo> voList = new ArrayList<>();
        for (ProductAppraise appraise : resultPage.getRecords()) {
            // 查询用户信息
            User user = userMapper.selectById(appraise.getUserId());
            String username = user != null ? user.getName() : "未知用户";
            
            // 查询商品信息
            Product product = productMapper.selectById(appraise.getProductId());
            String productName = product != null ? product.getName() : "未知商品";
            String productImage = product != null ? product.getImage() : null;
            
            // 构建VO对象
            ProductAppraiseVo vo = ProductAppraiseVo.builder()
                    .id(appraise.getId())
                    .username(username)
                    .rating(appraise.getRating())
                    .content(appraise.getContent())
                    .build();
            
            // 添加商品信息（需要先修改ProductAppraiseVo类）
             vo.setProductName(productName);
             vo.setProductImage(productImage);
            
            voList.add(vo);
        }
        
        // 创建新的Page对象返回
        Page<ProductAppraiseVo> voPage = new Page<>(page, pageSize);
        voPage.setRecords(voList);
        voPage.setTotal(resultPage.getTotal());
        voPage.setCurrent(resultPage.getCurrent());
        voPage.setSize(resultPage.getSize());
        
        return voPage;
    }

    @Override
    public void deleteAppraise(Long id) {
        // 直接删除评价
        productAppraiseMapper.deleteById(id);
    }
}